package javase.io;

import jdk.internal.util.xml.impl.Input;

import java.io.*;

/**
 * 字符数组输入输出流
 * @author LiShaowen
 * @date 2020/9/9 14:08
 */
public class ByteArrayIOTest {

    public static void main(String[] args) {

        byteArayToFile(fileToByteArray("src/main/java/javase/io/lsw.jpg"),"src/main/java/javase/io/lsw001.jpg");
    }
    // 文件转换成字符数组
    public static byte[] fileToByteArray(String filePath){
        // 1.创建源
        File file = new File(filePath);
        // 2.选择流
        ByteArrayOutputStream baos = null;
        InputStream is =null;
        try {
            is = new FileInputStream(file);
            baos = new ByteArrayOutputStream();
            // 3.操作（分段读取）
            byte[] flush = new byte[1024];
            int length;
            while ((length = is.read(flush)) != -1) {
                baos.write(flush,0,length);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (null!=baos) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null!=is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        baos = new ByteArrayOutputStream();

        return new byte[0];
    }
    public static void byteArayToFile(byte[] datas,String targetFilePath){
        // 1.创建源
        File file = new File(targetFilePath);

        // 2.选择流
        ByteArrayInputStream bais = null;
        OutputStream os =null;

        // 3.操作（写入）
        try {
            bais = new ByteArrayInputStream(datas);
            os = new FileOutputStream(file);
            byte[] flush = new byte[1024];
            int length;
            while ((length = bais.read(flush))!= -1) {
                os.write(flush);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (null!=os) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null!=bais) {
                    bais.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }




}
